﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using Timer = System.Timers.Timer;

namespace 第三次作业
{
    public class AlarmClock
    {
        private readonly Timer _timer;
        public DateTime AlarmTime { get; set; }
        public event EventHandler Tick;
        public event EventHandler Alarm;
        public AlarmClock(DateTime alarmTime)
        {
            AlarmTime = alarmTime;
            _timer = new Timer(1000);
            _timer.Elapsed += OnTimerElapsed;
        }

        public void Start()
        {
            _timer.Start();
            Console.WriteLine($"闹钟已启动，设定响铃时间为：{AlarmTime:HH:mm:ss}");
        }

        public void Stop()
        {
            _timer.Stop();
            Console.WriteLine("闹钟已停止");
        }

        private void OnTimerElapsed(object sender, ElapsedEventArgs e)
        {
            // 触发Tick事件
            Tick?.Invoke(this, EventArgs.Empty);

            // 检查是否到达响铃时间
            if (DateTime.Now >= AlarmTime)
            {
                // 触发Alarm事件
                Alarm?.Invoke(this, EventArgs.Empty);
                _timer.Stop(); // 响铃后停止计时器
            }
        }
    }

    internal class c5
    {
        static void Main()
        {
            DateTime alarmTime = DateTime.Now.AddMinutes(1).AddSeconds(-DateTime.Now.Second);
            var alarmClock = new AlarmClock(alarmTime);
            alarmClock.Tick += (s, e) =>
                Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] Tick...");
            alarmClock.Alarm += (s, e) =>
                Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] Alarm");
            alarmClock.Start();
            Console.WriteLine("按任意键退出...");
            Console.ReadKey();
            alarmClock.Stop();
        }
    }
}
